package com.cloud.hotline.api.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aspose.words.Bookmark;
import com.aspose.words.BookmarkCollection;
import com.aspose.words.CellCollection;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.NodeCollection;
import com.aspose.words.NodeType;
import com.aspose.words.Row;
import com.aspose.words.RowCollection;
import com.aspose.words.SaveFormat;
import com.aspose.words.Table;
import com.cloud.hotline.api.bean.HotlineCalculateBean;
import com.cloud.hotline.api.bean.HotlineCalculateForm;
import com.cloud.hotline.api.bean.HotlineStreetCaculateBean;
import com.cloud.hotline.api.bean.HotlineUnitCaculateBean;
import com.cloud.hotline.api.service.HotlineExportService;
import com.cloud.hotline.api.service.HotlineStatService;
import com.cloud.hotline.common.utils.DateHelper;

@Service
public class HotlineExportServiceImpl implements HotlineExportService {

	@Autowired
	private HotlineStatService hotlineStatService;

	@SuppressWarnings("unchecked")
	@Override
	public byte[] export(HotlineCalculateForm form) {
		Date end = form.getEnd();
		// 表格填充
		form.setType(1);
		// 诉求三率 -- 街道（市级回访）
		form.setResponseType(1); // 市级回访
		form.setKhType(0);
		List<HotlineCalculateBean> strCalcResults = (List<HotlineCalculateBean>) hotlineStatService.calculate(form);
		// 诉求三率 -- 部门（市级回访）
		form.setKhType(1);
		List<HotlineCalculateBean> unitCalcResults = (List<HotlineCalculateBean>) hotlineStatService.calculate(form);

		// 诉求三率 -- 街道（市区合计）
		form.setResponseType(0); // 区级回访
		form.setKhType(0);
		List<HotlineCalculateBean> strCalcAllResults = (List<HotlineCalculateBean>) hotlineStatService.calculate(form);
		// 诉求三率 -- 部门（市区合计）
		form.setKhType(1);
		List<HotlineCalculateBean> unitCalcAllResults = (List<HotlineCalculateBean>) hotlineStatService.calculate(form);

		// 街道承办
		form.setType(2);
		form.setEnd(end);
		List<HotlineStreetCaculateBean> street1234Results = (List<HotlineStreetCaculateBean>) hotlineStatService
				.calculate(form);

		// 部门承办
		form.setType(3);
		form.setEnd(end);
		List<HotlineUnitCaculateBean> unit1234Results = (List<HotlineUnitCaculateBean>) hotlineStatService
				.calculate(form);

		InputStream in = null;
		ByteArrayInputStream bis = null;
		ByteArrayOutputStream bos = null;
		Document doc = null;
		try {
			in = HotlineExportServiceImpl.class.getClassLoader().getResourceAsStream("template/template.docx");
			doc = new Document(in);
			// 诉求三率（街道）（市级回访）
			if (null != strCalcResults && strCalcResults.size() > 0) {
				this.fillSqslTable(doc, 0, strCalcResults);
			}
			// 诉求三率（部门）（市级回访）
			if (null != unitCalcResults && unitCalcResults.size() > 0) {
				this.fillSqslTable(doc, 1, unitCalcResults);
			}

			// 诉求三率（街道）（市区合计）
			if (null != strCalcAllResults && strCalcAllResults.size() > 0) {
				this.fillSqslTable(doc, 2, strCalcAllResults);
			}
			// 诉求三率（部门）（市区合计）
			if (null != unitCalcAllResults && unitCalcAllResults.size() > 0) {
				this.fillSqslTable(doc, 3, unitCalcAllResults);
			}

			// 12345工单统计
			if (null != street1234Results && street1234Results.size() > 0) {
				this.fill12345Street(doc, 4, street1234Results);
			}
			// 12345工单统计
			if (null != unit1234Results && unit1234Results.size() > 0) {
				this.fill12345Unit(doc, 5, unit1234Results);
			}

			Map<String, String> boomarkMap = new HashMap<String, String>();
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, 2019);
			calendar.set(Calendar.MONTH, 5);
			calendar.set(Calendar.DATE, 3);
			boomarkMap.put("期数", DateHelper.daysOfTwoDate(calendar.getTime(), new Date()) + "");
			boomarkMap.put("当前日期", DateHelper.dateToFormatStr(new Date(), "yyyy年MM月dd日"));
			boomarkMap.put("开始日期", DateHelper.dateToFormatStr(form.getStart(), "MM月dd日"));
			boomarkMap.put("结束日期", DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			boomarkMap.put("时间段", DateHelper.dateToFormatStr(form.getStart(), "MM月dd日") + "至"
					+ DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			
			boomarkMap.put("开始日期1", DateHelper.dateToFormatStr(form.getStart(), "MM月dd日"));
			boomarkMap.put("结束日期1", DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			boomarkMap.put("时间段1", DateHelper.dateToFormatStr(form.getStart(), "MM月dd日") + "至"
					+ DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			
			boomarkMap.put("开始日期2", DateHelper.dateToFormatStr(form.getStart(), "MM月dd日"));
			boomarkMap.put("结束日期2", DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			boomarkMap.put("时间段2", DateHelper.dateToFormatStr(form.getStart(), "MM月dd日") + "至"
					+ DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			
			boomarkMap.put("街道诉求总数", DateHelper.dateToFormatStr(form.getEnd(), "MM月dd日"));
			// 解决率、满意率、综合评分
			String jjl = "", myl = "", zhpf = "";
			if (strCalcResults.size() > 0) {
				HotlineCalculateBean bean = strCalcResults.get(strCalcResults.size() - 1);
				jjl = bean.getJjl();
				myl = bean.getMyl();
				zhpf = bean.getZhpf();
			}
			boomarkMap.put("街道解决率", jjl);
			boomarkMap.put("街道满意率", myl);
			boomarkMap.put("街道综合评分", zhpf);

			
			// 承办总数、 街道承办总数、 部门承办总数、今日承办总数、 今日街道承办总数、 今日部门承办总数
			int cbzs = 0, jdcbzs = 0, bmcbzs = 0, jrcbzs = 0, jrjdcbzs = 0, jrbmcbzs = 0;
			if (street1234Results.size() > 0) {
				HotlineStreetCaculateBean streetTotal = street1234Results.get(street1234Results.size() - 1);
				cbzs += streetTotal.getLjsl();
				jdcbzs = streetTotal.getLjsl();
				jrjdcbzs = streetTotal.getJrzs();
			}

			if (unit1234Results.size() > 0) {
				HotlineUnitCaculateBean unitTotal = unit1234Results.get(unit1234Results.size() - 1);
				cbzs += unitTotal.getLjsl();
				bmcbzs = unitTotal.getLjsl();
				jrbmcbzs = unitTotal.getJrzs();
			}

			boomarkMap.put("承办总数", cbzs + "");
			boomarkMap.put("街道承办总数", jdcbzs + "");
			boomarkMap.put("部门承办总数", bmcbzs + "");

			boomarkMap.put("今日承办总数", jrcbzs + "");
			boomarkMap.put("今日街道承办总数", jrjdcbzs + "");
			boomarkMap.put("今日部门承办总数", jrbmcbzs + "");

			BookmarkCollection bookMarks = doc.getRange().getBookmarks();
			Iterator<Bookmark> it = bookMarks.iterator();
			while (it.hasNext()) {
				Bookmark mark = it.next();
				String markName = mark.getName();
				if (boomarkMap.containsKey(markName)) {
					if (boomarkMap.get(markName) != null) {
						String value = boomarkMap.get(markName) + "";
						mark.setText(value);
					} else {
						mark.setText("");
					}
				}
			}
			bos = new ByteArrayOutputStream();
			doc.save(bos, SaveFormat.DOC);
			bos.flush();
			return bos.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (null != bis) {
					bis.close();
				}
				if (null != bos) {
					bos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 填充模板中的12345热线统计情况（街道）
	 * 
	 * @param doc
	 * @param tableIndex
	 * @param strCaclResults
	 */
	private void fill12345Unit(Document doc, int tableIndex, List<HotlineUnitCaculateBean> strCaclResults) {
		DocumentBuilder builder = new DocumentBuilder(doc);
		@SuppressWarnings("rawtypes")
		NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
		Table table = (Table) allTables.get(tableIndex);
		RowCollection rows = table.getRows();
		for (int i = 0; i < strCaclResults.size() - 1; i++) {
			HotlineUnitCaculateBean result = strCaclResults.get(i);
			Row row = rows.get(i + 1);
			if (i < strCaclResults.size() - 2) {
				Row cloneRow1 = (Row) row.deepClone(true);
				rows.insert(i + 2, cloneRow1);
			}
			CellCollection cells = row.getCells();
			builder.moveTo(cells.get(0).getFirstChild());
			builder.write(result.getPm() + "");
			builder.moveTo(cells.get(1).getFirstChild());
			builder.write(result.getMc() + "");
			builder.moveTo(cells.get(2).getFirstChild());
			builder.write(result.getJrzs() + "");
			builder.moveTo(cells.get(3).getFirstChild());
			builder.write(result.getLjsl() + "");
		}
		if (null != strCaclResults && strCaclResults.size() > 1) {
			HotlineUnitCaculateBean summary = strCaclResults.get(strCaclResults.size() - 1);
			Row row = rows.get(strCaclResults.size());
			CellCollection cells = row.getCells();
			builder.moveTo(cells.get(1).getFirstChild());
			builder.write(summary.getJrzs() + "");
			builder.moveTo(cells.get(2).getFirstChild());
			builder.write(summary.getLjsl() + "");
		}
	}

	/**
	 * 填充模板中的12345热线统计情况（街道）
	 * 
	 * @param doc
	 * @param tableIndex
	 * @param strCaclResults
	 */
	private void fill12345Street(Document doc, int tableIndex, List<HotlineStreetCaculateBean> strCaclResults) {
		DocumentBuilder builder = new DocumentBuilder(doc);
		@SuppressWarnings("rawtypes")
		NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
		Table table = (Table) allTables.get(tableIndex);
		RowCollection rows = table.getRows();
		for (int i = 0; i < strCaclResults.size() - 1; i++) {
			HotlineStreetCaculateBean result = strCaclResults.get(i);
			Row row = rows.get(i + 1);
			if (i < strCaclResults.size() - 2) {
				Row cloneRow1 = (Row) row.deepClone(true);
				rows.insert(i + 2, cloneRow1);
			}
			CellCollection cells = row.getCells();
			builder.moveTo(cells.get(0).getFirstChild());
			builder.write(result.getPm() + "");
			builder.moveTo(cells.get(1).getFirstChild());
			builder.write(result.getJdmc() + "");
			builder.moveTo(cells.get(2).getFirstChild());
			builder.write(result.getJrzs() + "");
			builder.moveTo(cells.get(3).getFirstChild());
			builder.write(result.getJrszps() + "");
			builder.moveTo(cells.get(4).getFirstChild());
			builder.write(result.getJrqzps() + "");
			builder.moveTo(cells.get(5).getFirstChild());
			builder.write(result.getLjsl() + "");
		}
		if (null != strCaclResults && strCaclResults.size() > 0) {
			HotlineStreetCaculateBean summary = strCaclResults.get(strCaclResults.size() - 1);
			Row row = rows.get(strCaclResults.size());
			CellCollection cells = row.getCells();
			builder.moveTo(cells.get(1).getFirstChild());
			builder.write(summary.getJrzs() + "");
			builder.moveTo(cells.get(2).getFirstChild());
			builder.write(summary.getJrszps() + "");
			builder.moveTo(cells.get(3).getFirstChild());
			builder.write(summary.getJrqzps() + "");
			builder.moveTo(cells.get(4).getFirstChild());
			builder.write(summary.getLjsl() + "");
		}
	}

	/**
	 * 填充模板中的诉求三率统计情况
	 * 
	 * @param doc
	 * @param tableIndex
	 * @param strCalcResults
	 */
	private void fillSqslTable(Document doc, int tableIndex, List<HotlineCalculateBean> strCalcResults) {
		DocumentBuilder builder = new DocumentBuilder(doc);
		@SuppressWarnings("rawtypes")
		NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
		Table table = (Table) allTables.get(tableIndex);
		RowCollection rows = table.getRows();
		for (int i = 0; i < strCalcResults.size() - 1; i++) {
			HotlineCalculateBean result = strCalcResults.get(i);
			Row row = rows.get(i + 1);
			if (i < strCalcResults.size() - 2) {
				Row cloneRow1 = (Row) row.deepClone(true);
				rows.insert(i + 2, cloneRow1);
			}
			CellCollection cells = row.getCells();
			builder.moveTo(cells.get(0).getFirstChild());
			builder.write(result.getPm() + "");
			builder.moveTo(cells.get(1).getFirstChild());
			builder.write(result.getDw() + "");
			builder.moveTo(cells.get(2).getFirstChild());
			builder.write(result.getYxf() + "");
			builder.moveTo(cells.get(3).getFirstChild());
			builder.write(result.getXyl() + "");
			builder.moveTo(cells.get(4).getFirstChild());
			builder.write(result.getJjs() + "");
			builder.moveTo(cells.get(5).getFirstChild());
			builder.write(result.getJjl() + "");
			builder.moveTo(cells.get(6).getFirstChild());
			builder.write(result.getMys() + "");
			builder.moveTo(cells.get(7).getFirstChild());
			builder.write(result.getMyl() + "");
			builder.moveTo(cells.get(8).getFirstChild());
			builder.write(result.getZhpf() + "");
			builder.moveTo(cells.get(9).getFirstChild());
			builder.write(result.getSlhj() + "");
			builder.moveTo(cells.get(10).getFirstChild());
			builder.write(result.getYjscz() + "");
		}
		if (null != strCalcResults && strCalcResults.size() > 1) {
			HotlineCalculateBean summary = strCalcResults.get(strCalcResults.size() - 1);
			Row row = rows.get(strCalcResults.size());
			CellCollection cells = row.getCells();
			builder.moveTo(cells.get(1).getFirstChild());
			builder.write(summary.getYxf() + "");
			builder.moveTo(cells.get(2).getFirstChild());
			builder.write(summary.getXyl() + "");
			builder.moveTo(cells.get(3).getFirstChild());
			builder.write(summary.getJjs() + "");
			builder.moveTo(cells.get(4).getFirstChild());
			builder.write(summary.getJjl() + "");
			builder.moveTo(cells.get(5).getFirstChild());
			builder.write(summary.getMys() + "");
			builder.moveTo(cells.get(6).getFirstChild());
			builder.write(summary.getMyl() + "");
			builder.moveTo(cells.get(7).getFirstChild());
			builder.write(summary.getZhpf() + "");
			builder.moveTo(cells.get(8).getFirstChild());
			builder.write(summary.getSlhj() + "");
			builder.moveTo(cells.get(9).getFirstChild());
			builder.write(summary.getYjscz() + "");
		}
	}

}
